package com.example.service.exam.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.example.domain.exam.Exam;
import com.example.domain.exam.dto.ExamQueryDTO;
import com.example.domain.exam.dto.ExamRankDTO;
import com.example.domain.exam.vo.ExamRankVO;
import com.example.domain.exam.vo.ExamVO;
import com.example.domain.user.vo.UserVO;
import com.example.manager.ExamCacheManager;
import com.example.manager.UserCacheManager;
import com.example.mapper.exam.ExamMapper;
import com.example.mapper.exam.ExamQuestionMapper;
import com.example.mapper.user.UserExamMapper;
import com.example.redis.service.RedisService;
import com.example.service.exam.IExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import oj.common.core.contants.JwtConstants;
import oj.common.core.domain.TableDataInfo;
import oj.common.core.utils.ThreadLocalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ExamServiceImpl implements IExamService {
    private static final Logger log = LoggerFactory.getLogger(ExamServiceImpl.class);
    @Autowired
    private ExamCacheManager examCacheManager;
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ExamQuestionMapper examQuestionMapper;
    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
       PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
        return examMapper.selectExamList(examQueryDTO);
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        //首先现在redis中查询，如果不存在去mysql去查询。
        Long total = examCacheManager.getListSize(examQueryDTO.getType(),null);
        Long userId = ThreadLocalUtil.get(JwtConstants.LOGIN_USER_ID, Long.class);
        List<ExamVO> examVOList;
        if(total==null || total<=0) {
            //此时需要从数据库中拿数据
            examVOList = list(examQueryDTO);
            examCacheManager.refreshCache(examQueryDTO.getType(),null);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            //直接从缓存中拿取数据
            examVOList = examCacheManager.getExamVOList(examQueryDTO,null);
            total = examCacheManager.getListSize(examQueryDTO.getType(),null);
        }
        if(CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        //当进行没有登录的时候会导致数据刷新不出
        if(userId!=null) {
            assembleExamVOList(examVOList,userId);
        }
        return TableDataInfo.success(examVOList,total);
    }

    @Override
    public String getFirstQuestion(Long examId) {
        //首先是判断是从数据库中拿取数据还是从redis拿取数据
        Exam exam = examMapper.selectById(examId);
        if(BeanUtil.isEmpty(exam)) {
            return null;
        }
        //这里的话因为在撤销发布的时候删除缓存，然后在点击发布的时候也并不会去维护缓存
        //当点击开始答题的时候才会去维持缓存
        Long count = examCacheManager.getQuestionExamListSize(examId);
        if (count == null || count<=0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
      return examCacheManager.getFirstQuestion(examId).toString();
    }

    @Override
    public String preQuestionDetail(Long examId, Long questionId) {
        Long count = examCacheManager.getQuestionExamListSize(examId);
        if(count==null || count<=0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
        return examCacheManager.preQuestion(examId,questionId).toString();
    }

    @Override
    public String nextQuestionDetail(Long examId, Long questionId) {
        Long count = examCacheManager.getQuestionExamListSize(examId);
        if(count==null || count<=0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
        return examCacheManager.nextQuestion(examId,questionId).toString();
    }

    @Override
    public TableDataInfo rankList(ExamRankDTO examRankDTO) {
        Long total = examCacheManager.getExamRankListSize(examRankDTO.getExamId());
        List<ExamRankVO> examRankVOList;
        if(total==null || total<=0) {
            //此时需要从数据库中拿数据
            PageHelper.startPage(examRankDTO.getPageNum(), examRankDTO.getPageSize());
            examRankVOList =  userExamMapper.selectExamRankList(examRankDTO.getExamId());
            log.info("examRankListVO为"+examRankVOList.toString());
            examCacheManager.refreshExamRankCache(examRankDTO);
            total = new PageInfo<>(examRankVOList).getTotal();
        } else {
            //直接从缓存中拿取数据
            examRankVOList = examCacheManager.getExamRankList(examRankDTO);
        }
        if(CollectionUtil.isEmpty(examRankVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamRankVOList(examRankVOList);
        return TableDataInfo.success(examRankVOList,total);
    }

    private void assembleExamRankVOList(List<ExamRankVO> examRankVOList) {
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return;
        }
        for (ExamRankVO examRankVO : examRankVOList) {
            Long userId = examRankVO.getUserId();
            UserVO user = userCacheManager.getUserVOById(userId);
            examRankVO.setNickName(user.getNickName());
        }
    }

    private void assembleExamVOList(List<ExamVO> examVOList,Long userId) {
        List<Long> examIdList = examCacheManager.getAllExamList(userId);
        if(CollectionUtil.isEmpty(examVOList)) {
            return ;
        }
        if(CollectionUtil.isEmpty(examIdList)) {
            return ;
        }

        for(ExamVO examVO : examVOList) {
            //这里先在redis中查询到id然后再进行匹配。
            if(examIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }
}
